package com.kartoshka.core 
{
	import com.kartoshka.painters.BackgroundGradientPainter;
	import com.kartoshka.interfaces.IPainter;
	import com.kartoshka.utils.CoreUtil;
	import com.kartoshka.managers.ValidationManager;
	import com.kartoshka.interfaces.IValidatable;
	import com.kartoshka.core.hard.UISprite;

	import flash.display.DisplayObject;
	import flash.events.Event;

	/**
	 * @author Alexander Zats, 2009
	 */
	public class Application extends UISprite implements IValidatable
	{

		protected var _validationManager : ValidationManager;
		private const _uid : String = CoreUtil.getUid( this );
		private var _background : IPainter;

		public function Application()
		{
			super( );
			this.addEventListener( Event.ADDED_TO_STAGE, onStage, false, 0, true );
			_background = new BackgroundGradientPainter( [ 0xFFFFFF, 0xDDDDDD ], 0, "radial", 0, 0.5 );
		}

		private function onStage(event : Event) : void
		{
			this.removeEventListener( Event.ADDED_TO_STAGE, onStage, false );

			stage.align = "TL";
			stage.scaleMode = "noScale";
			
			_validationManager = ValidationManager.instance;

			stage.addEventListener( Event.RESIZE, onStageResize, false, 0, true );
			this.onStageResize( null );
		}

		private function onStageResize(event : Event) : void
		{
			this.graphics.clear( );
			_background.draw( this.graphics, width, height );
			//			invalidate( );
			validate( true );
		}

		public function invalidate( flag : int ) : void
		{
			_validationManager.addToQueue( this );
		}

		public function validate( force : Boolean = false ) : void
		{
			var child : DisplayObject;
			for ( var i : int = 0; i < this.numChildren ; i++ )
			{
				child = this.getChildAt( i );
				if ( ! ( child is IValidatable ) ) continue;
				if ( ValidationManager.resizeTriggerImmediateValidation )
				{
					( child as IValidatable ).validate( true );
				}
				else
				{
					( child as IValidatable ).invalidate( ValidationManager.ALL );
				}
			}
		}

		override public function set width( value : Number ) : void
		{
		}

		override public function get width() : Number
		{
			return stage.stageWidth;
		}

		override public function set height( value : Number ) : void
		{
		}

		override public function get height() : Number
		{
			return stage.stageHeight;
		}

		public final function get uid() : String
		{
			return _uid;
		}

		public function get background() : IPainter
		{
			return _background;
		}

		public function set background(background : IPainter) : void
		{
			_background = background;
		}
	}
}
